// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "worker_pool.h"

#include "glog/logging.h"
#include "worker.h"

namespace seven_summits {

WorkerPool::WorkerPool(int num_workers, WorkerFactory* factory)
    : num_workers_(num_workers),
      workers_(new Worker*[num_workers_]),
      next_worker_(0) {
  for (int i = 0; i < num_workers; ++i) {
    workers_[i] = factory->ConstructWorker();
  }
  pthread_mutex_init(&mutex_, NULL);
}

WorkerPool::~WorkerPool() {
  for (int i = 0; i < num_workers_; ++i) {
    delete workers_[i];
  }
  delete [] workers_;
}

void WorkerPool::Init() {
  for (int i = 0; i < num_workers_; ++i) {
    workers_[i]->Init();
  }
}

Worker* WorkerPool::GetWorker() {
  pthread_mutex_lock(&mutex_);
  VLOG(2) << "next worker: " << next_worker_;
  Worker* worker = workers_[next_worker_];
  ++next_worker_;
  if (next_worker_ == num_workers_) {
    next_worker_ = 0;
  }
  pthread_mutex_unlock(&mutex_);
  return worker;
}

}  // namespace seven_summits
